
#include <stdio.h>

#include "common/checked_fileops.h"
#include "filedb.h"

static void usage()
{
    fprintf(stdout, "usage: query {db-file-name}\n");
}

static bool prn_receiver(const char * str)
{
    fprintf(stdout, "%s\n", str);
    return true;
}

static void remove_newline(char * str)
{
    while (*str != 0)
    {
        if (*str == '\n')
        {
            *str = 0;
            break;
        }
        ++str;
    }
}

int main(int argc, char ** argv)
{
#ifdef _DEBUG
    argc = 2;
    char * argv2[] = { "", "test" };
    argv = argv2;
#endif

    int result = 0;
    const char * src_filename = NULL;
    FILE * fsrc = NULL;

    if (argc < 2)
    {
        fprintf(stderr, "error: destination filename is not specified");
        usage();
        result = -1;
    }
    else
    {
        src_filename = argv[1];
    }

    // open source files
    CHECKED_OPEN_READ(fsrc, src_filename);

    struct FileDb * db = NULL;
    if (!result)
    {
        db = load_file_db(fsrc, prn_receiver);
        if (db == NULL)
        {
            result = -1;
        }
    }

    if (!result)
    {
        for (;;)
        {
            char buf[256];
            fprintf(stdout, "> ");
            char * query = fgets(buf, 256, stdin);
            remove_newline(query);

            if (*query == 0)
            {
                // empty string entered
                fputs("empty string entered - now quit\n", stderr);
                break;
            }

            fputs("\n", stdout);
            file_db_query(db, query);
        }
    }

    // free resources
    CHECKED_CLOSE(fsrc);
    free_file_db(db);

    return result;
}
